layui.use(['jquery','layer', 'element', 'http', 'index', 'admin', 'laytpl','tools'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var element = layui.element;
    var index = layui.index;
    var admin = layui.admin;
    var laytpl = layui.laytpl;
    var device = layui.device();
    var tools = layui.tools;
    var http = layui.http;

    // 检查是否登录
    var isLogined = http.getToken();
    if (!isLogined) {
        return location.replace('login.html');
    }else{
        http.get('user/checkLogin',{},function(res){
            if(!res.ok){
                return location.replace('login.html');
            }
        });
    }

    //解决 IE8 不支持console
    if(device.ie && device.ie < 9) {
        window.console = window.console || (function () {
            var c = {};
            c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile
                = c.clear = c.exception = c.trace = c.assert = function () {
            };
            return c;
        })();
    }
    var stopIt = function stopIt(ev){
        if(ev.preventDefault ){
            //preventDefault()方法阻止元素发生默认的行为
            ev.preventDefault();
            ev.stopPropagation();
        }
        if(ev.returnValue){
            //IE浏览器下用window.event.returnValue = false;实现阻止元素发生默认的行为
            ev.cancelBubble=true;
            ev.returnValue = false;
        }
        return false;
    }


    //禁止Backspace键使浏览器后退
    var banBackSpace = function(e){
        var ev = e || window.event;
        //各种浏览器下获取事件对象
        var obj = ev.relatedTarget || ev.srcElement || ev.target ||ev.currentTarget;
        //按下Backspace键
        if(ev.keyCode == 8){
            var tagName = obj.nodeName //标签名称
            //如果标签不是input或者textarea则阻止Backspace
            if(tagName!='INPUT' && tagName!='TEXTAREA'){
                return stopIt(ev);
            }
            var tagType = obj.type.toUpperCase();//标签类型
            //input标签除了下面几种类型，全部阻止Backspace
            if(tagName=='INPUT' && (tagType!='TEXT' && tagType!='TEXTAREA' && tagType!='PASSWORD')){
                return stopIt(ev);
            }
            //input或者textarea输入框如果不可编辑则阻止Backspace
            if((tagName=='INPUT' || tagName=='TEXTAREA') && (obj.readOnly==true || obj.disabled ==true)){
                return stopIt(ev);
            }
        }
    };

    //屏蔽backspace: IE，firefox，opera
    if(device.ie || tools.browser.isFirefox || tools.browser.isOpera || tools.browser.isEdge) {
        //实现对字符码的截获，keypress中屏蔽了这些功能按键
        document.onkeypress = banBackSpace;
        //对功能按键的获取
        document.onkeydown = banBackSpace;
    }

    var addSubMenus = function(data,parentItem){
        for(var i=0;i<data.length;i++){
            var item = data[i];
            if(item.parentId === parentItem.id){
                if(!parentItem.subMenus){
                    parentItem.subMenus = [];
                }
                parentItem.subMenus.push(item);
                addSubMenus(data,item);
            }
        }
    };

    isLogined && http.get('user/getIndexPageData',{},function(res){
       if(res.ok){
           var userInfo = res.data.userInfo;
           http.putUser(userInfo);
           http.putDeptCodeList(res.data.deptCodeList);
           $('#userName').text(userInfo.userName);

           var menuList = res.data.menuList;
           var mData = [];
           for(var i=0;i<menuList.length;i++){
               var item = menuList[i];
               if(item.parentId === 0){
                   mData.push(item);
                   addSubMenus(menuList,item)
               }
           }
           laytpl(sideNav.innerHTML).render(mData, function (html) {
               $('.layui-layout-admin .layui-side .layui-nav').html(html);
               element.render('nav');
           });
           index.regRouter(mData);  // 注册路由
           var defaultPage = userInfo.defaultPage;
           if(defaultPage) {
               index.loadHome({  // 加载主页
                   url: defaultPage,
                   name: '<i class="layui-icon layui-icon-home"></i>'
               });
           }
       }
    });

    // 加载侧边栏
    /*
    isLogined && http.get('menus.json', {}, function (data) {
        laytpl(sideNav.innerHTML).render(data, function (html) {
            $('.layui-layout-admin .layui-side .layui-nav').html(html);
            element.render('nav');
        });
        index.regRouter(data);  // 注册路由
        index.loadHome({  // 加载主页
            url: '#/console/console1',
            name: '<i class="layui-icon layui-icon-home"></i>'
        });
    });
    */

    // 退出登录
    $('#index-header [data-id="index-btnLogout"]').click(function () {
        layer.confirm('确定退出登录？', {
            skin: 'layui-layer-admin'
        }, function () {
            http.post('user/logout',{},function (res) {
                if(res.ok) {
                    http.removeToken();
                    location.replace('login.html');
                }
            });
        });
    });

    // 修改密码
    $('#index-header [data-id="index-btnSetPsw"]').click(function () {
        admin.open({
            id: 'pswDialog',
            title: '修改密码',
            shade: 0,
            url: 'views/tpl/password.html'
        });
    });

    // 重新登录
    $('#index-header [data-id="index-btnReLogin"]').click(function () {
        http.reLogin();
    });

    // 移除loading动画
    setTimeout(function () {
        admin.removeLoading();
        // 提示
        // if (!http.pageTabs) {
        //     layer.confirm('SPA版本默认关闭多标签功能，你可以在设置界面开启', {
        //         skin: 'layui-layer-admin',
        //         area: '280px',
        //         title: '温馨提示',
        //         shade: 0,
        //         btn: ['打开设置', '知道了']
        //     }, function (i) {
        //         layer.close(i);
        //         $('a[ew-event="theme"]').trigger('click');
        //     });
        // }
    }, 300);


    $('body').on('click', 'a[lay-href]', function () {
        var path = $(this).attr('lay-href');
        if(path.length>0 && path != "javascript:;"){
            if(path[0] == "#"){
                index.go(path.substring(1));
            }else{
                window.open(path);
            }
        }
        return false;
    });
});
